package com.zxxy.gulimall.testssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @RequestMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirect_url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)){
            return "redirect:"+redirect_url+"?token="+sso_token;
        }

        model.addAttribute("url",redirect_url);

        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(HttpSession session, @RequestParam("username") String username,
                          @RequestParam("password")String password, String url,
                          HttpServletResponse response){

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            session.setAttribute("loginUser","haode");
            // 登录成功跳转，跳回到之前的页面
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid,username);
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:"+url+"?token="+uuid;
        }
        // 登录失败调到登录页
        return "login";
    }


}
